package com.chenl.consumer.util;

import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class HttpUtils {
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class HttpResult {
        private Integer code;
        private String message;
        private Object data;

        public static HttpResult success() {
            return new HttpResult(0, "success", null);
        }

        public static HttpResult success(Integer code, String message, Object data) {
            HttpResult httpResult = new HttpResult();
            if (code != null) {
                httpResult.setCode(code);
            } else {
                httpResult.setCode(0);
            }
            if (message != null) {
                httpResult.setMessage(message);
            } else {
                httpResult.setMessage("success");
            }
            if (message != null) {
                httpResult.setData(data);
            } else {
                httpResult.setData(null);
            }
            return httpResult;
        }

        public static HttpResult error(String errorMsg) {
            HttpResult result = new HttpResult(1, "error", null);
            if (errorMsg != null) {
                result.setMessage(errorMsg);
            }
            return result;
        }
    }

    /**
     * 发送Post请求
     *
     * @param url          URL
     * @param object       要发送的数据 可为null
     * @param headersMap   请求头  可为null
     * @param restTemplate restTemplate
     * @return
     */
    public static HttpResult PostHttp(String url, Object object, Map<String, String> headersMap, RestTemplate restTemplate, Class<? extends Object> clazz) {//post请求发送对象并添加请求头
        HttpHeaders headers = new HttpHeaders();
        if (headersMap != null && headersMap.get("Content-Type") != null) {
            headers.setContentType(MediaType.parseMediaType(headersMap.get("Content-Type")));
        } else {
            headers.setContentType(MediaType.APPLICATION_JSON);
        }
        if (headersMap != null && headersMap.size() > 0) {
            for (Map.Entry<String, String> entry : headersMap.entrySet()) {
                headers.add(entry.getKey(), entry.getValue());
            }
        }
        HttpEntity<String> strEntity = new HttpEntity<>(JSONObject.toJSONString(object), headers);
        ResponseEntity<? extends Object> responseEntity = null;
        try {
            responseEntity = restTemplate.exchange(url, HttpMethod.POST, strEntity, clazz);
        } catch (RestClientException e) {
            return HttpResult.error(e.toString());
        }
        if (String.valueOf(responseEntity.getStatusCode().value()).equals("200")) {
            if (responseEntity.getBody() != null) {
                return HttpResult.success(0, "success", responseEntity.getBody());
            }
            return HttpResult.success();
        } else {
            return HttpResult.error(responseEntity.toString());
        }
    }

    public static Map<String, Object> GetHttp(String url, Map<String, String> map, Map<String, String> headersMap) {//get请求带路径参数和请求头
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        if (JSONObject.toJSONString(headersMap).contains("content")) {
            headers.setContentType(MediaType.APPLICATION_JSON);
        }
        if (headersMap != null && headersMap.size() > 0) {
            for (Map.Entry<String, String> entry : headersMap.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                headers.add(key, value);
            }
        }
        HttpEntity<MultiValueMap> httpEntity = new HttpEntity<>(null, headers);
        if (map.size() > 0) {
            url += "?";
            for (Map.Entry<String, String> stringStringEntry : map.entrySet()) {
                String key = stringStringEntry.getKey();
                String value = stringStringEntry.getValue();
                url += key + "=" + value + "&";
            }
        }
        url = url.substring(0, url.length() - 1);
        log.info("getHttpUrl---:{}", url);
        ResponseEntity<String> forEntity = null;
        Map<String, Object> respMap = new HashMap<>();
        try {
            forEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
        } catch (RestClientException e) {
            respMap.put("exception", e.toString());
            return respMap;
        }
        String body = forEntity.getBody();
        HttpStatus statusCode = forEntity.getStatusCode();
        respMap.put("body", body);
        respMap.put("statusCode", statusCode);
        return respMap;
    }
}